package cn.jhc.controller;

import java.util.ArrayList;
import java.util.List;

import cn.jhc.bean.CartItemBean;
import cn.jhc.bean.MsgBean;
import cn.jhc.bean.ShopBean;
import cn.jhc.dao.ConnectionFactory;
import cn.jhc.dao.TitleDAO;

public class Cart {

	private List<CartItemBean> list;
	private CartItemBean sum;
	
	public Cart() {
		list = new ArrayList<CartItemBean>();
		sum = new CartItemBean();

	}
	
	public void addToCart(String isbn) {
		TitleDAO dao = new TitleDAO();
		dao.setCon(ConnectionFactory.getConnection());
		ShopBean title = dao.getTitle(isbn);
		CartItemBean tmp = findItem(isbn);
		if( tmp == null ) {
			CartItemBean item = new CartItemBean();
			item.setAmcount(1);
			item.setSubtotal(title.getPrice());
			list.add(item);
		}
		else {
			tmp.setAmcount(tmp.getAmcount()+1);
			tmp.setSubtotal(tmp.getAmcount()*title.getPrice());
		}
	}		
	
	private CartItemBean findItem(String isbn) {
		CartItemBean item = null;
		for( CartItemBean t : list ) {
			if(t.getTitle().getIsbn().equals(isbn)){
				return t;
				}
		}
		return item;
	}
	public void addCart(String isbn){
		TitleDAO dao = new TitleDAO();
		dao.setCon(ConnectionFactory.getConnection());
		ShopBean title = dao.getTitle(isbn);
		CartItemBean tmp = findItem2(isbn);
		if( tmp == null ) {
			sum.setTotal(title.getPrice());
		}
		else {
			sum.setTotal(sum.getTotal()+title.getPrice());
		}
	}

	private CartItemBean findItem2(String isbn) {
		CartItemBean item2 = null;
		for( CartItemBean t : list ) {
			if(t.getTitle().getIsbn().equals(isbn)){
				return t;
				}else{
					return t;
				}
		}
		return item2;
	}
	
	public void addDelCart(String isbn) {
		TitleDAO dao = new TitleDAO();
		dao.setCon(ConnectionFactory.getConnection());
		ShopBean title = dao.getTitle(isbn);
		CartItemBean tmp = findItem(isbn);
		if( tmp != null ) {
				tmp.setAmcount(tmp.getAmcount()-1);
				tmp.setSubtotal(title.getPrice()*tmp.getAmcount());
				sum.setTotal(sum.getTotal()-title.getPrice());
		}else{
			return;
		}
	}
	
	public List<CartItemBean> getItems(){
		return list;
	}
	public CartItemBean getItem(){
		return sum;
	}

}
